package com.example.handler;

import com.example.request.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

public class RpcHandler extends SimpleChannelInboundHandler<RpcRequest> {


    private ApplicationContext applicationContext;

    public RpcHandler(ApplicationContext context) {
        this.applicationContext = context;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcRequest rpcRequest) throws Exception {
        System.out.println("request class " + rpcRequest.getClassName());
        // 获取服务实现类
        Object bean = applicationContext.getBean(Class.forName(rpcRequest.getClassName()));
        String methodName = rpcRequest.getMethodName();
        // 获取服务的方法
        Method method = bean.getClass().getMethod(methodName, rpcRequest.getParameterTypes());
        // 调用服务方法
        Object result = method.invoke(bean, rpcRequest.getParameters());
        // 响应
        channelHandlerContext.writeAndFlush(result);
    }

}
